package com.mpp.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mpp.admin.entity.*;
import com.mpp.admin.service.GeneratorService;
import com.mpp.admin.util.Generator;
import freemarker.template.TemplateException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * @author mapp
 * @des 代码生成器
 * @date 2019/3/13
 */
@Controller
@RequestMapping("/gen")
public class GeneratorController {

    @Autowired
    private GeneratorService generatorService;

    @RequestMapping("/index")
    public String index() {
        return "gencode";
    }

    @RequestMapping("/column")
    public String column(String dataBaseName, String tableName, ModelMap modelMap) {
        modelMap.put("columns", generatorService.columneList(dataBaseName, tableName));
        modelMap.put("tableName", tableName);
        modelMap.put("className", Generator.convertJavaClassName(tableName));
        return "column";
    }

    /**
     * 表信息
     * @param page
     * @param limit
     * @param dataBaseName
     * @return
     */
    @RequestMapping("/getTable")
    @ResponseBody
    public PageEntity getTable(Integer page, Integer limit, String dataBaseName) {
        return (PageEntity) generatorService.tableList(PageEntity.build(page, limit), dataBaseName);
    }

    /**
     * 生成代码
     * @param table
     * @param response
     */
    @RequestMapping("/genearte")
    @ResponseBody
    public void genearte(Table table, HttpServletResponse response) {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
             ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
             OutputStream out = response.getOutputStream()) {
            // 生成代码
            Generator.generate(table, zipOutputStream);

            byte[] data = outputStream.toByteArray();
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"code.zip\"");
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");
            out.write(data);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
